package com.onlyxiahui.extend.hibernate.boot.model.naming;

import org.hibernate.boot.model.naming.Identifier;
import org.hibernate.boot.model.naming.PhysicalNamingStrategy;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;

/**
 * 
 * <br>
 * Date 2019-07-18 14:07:26<br>
 * 
 * @author XiaHui [onlovexiahui@qq.com]<br>
 * @since 1.0.0
 */

public class UnderlinePhysicalNamingStrategy implements PhysicalNamingStrategy {
	final String regex = "([a-z])([A-Z])";
	final String replacement = "$1_$2";

	@Override
	public Identifier toPhysicalCatalogName(final Identifier identifier, final JdbcEnvironment jdbcEnv) {
		return convertToSnakeCase(identifier);
	}

	@Override
	public Identifier toPhysicalColumnName(final Identifier identifier, final JdbcEnvironment jdbcEnv) {
		return convertToSnakeCase(identifier);
	}

	@Override
	public Identifier toPhysicalSchemaName(final Identifier identifier, final JdbcEnvironment jdbcEnv) {
		return convertToSnakeCase(identifier);
	}

	@Override
	public Identifier toPhysicalSequenceName(final Identifier identifier, final JdbcEnvironment jdbcEnv) {
		return convertToSnakeCase(identifier);
	}

	@Override
	public Identifier toPhysicalTableName(final Identifier identifier, final JdbcEnvironment jdbcEnv) {
		return convertToSnakeCase(identifier);
	}

	private Identifier convertToSnakeCase(final Identifier identifier) {
		String name = (null == identifier) ? null : identifier.getText();
		if (null == name) {
			return identifier;
		} else {
			name = name.replaceAll(regex, replacement).toLowerCase();
			return Identifier.toIdentifier(name);
		}
	}
}
